package net.kansun.impl;

import net.kansun.Parser;

/**
 * The top level {@link Parser} implementation that orchestrates usages of relevant {@link Parser}
 * instances on different parts of the input number. '0 -> zero' conversion is handled here so that
 * downstream logic can be separated from concerns regarding handling zeros accurately.
 */
public class ParserController implements Parser {

   private Parser segmentParser;

   @Override
   public String parse(Long source) {

      if (source == 0) {
         return "zero";
      }

      final StringBuilder sb = new StringBuilder("");

      final Long megabits = source / 1000000;
      final Long kilobits = source % 1000000 / 1000;
      final Long centumbits = source % 1000;

      final String partI = segmentParser.parse(megabits);
      final String partII = segmentParser.parse(kilobits);
      final String partIII = segmentParser.parse(centumbits);

      if (partI.length() > 0) {
         sb.append(partI + " million ");
      }

      if (partII.length() > 0) {
         sb.append(partII + " thousand ");
      }

      if (partIII.length() > 0) {

         if ((partI.length() > 0 || partII.length() > 0) && centumbits < 100) {
            sb.append("and ");
         }
         sb.append(partIII);
      }

      return sb.toString().trim();
   }

   public void setSegmentParser(Parser segmentParser) {
      this.segmentParser = segmentParser;
   }

}
